import storage from 'store'
import { login, getInfo } from '@/api/user'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import store from '../index'

const state = {
  token: storage.get('token'),
  roles: storage.get('roles') || [],
  userInfo: localStorage.getItem('user_info') ? JSON.parse(localStorage.getItem('user_info')) : {},
  messageNum: 0
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_MEEEAGENUM: (state, messageNum) => {
    state.messageNum = messageNum
  }
}

const actions = {
  // user login
  Login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        if (response.code === 'A00000') {
          const { data } = response
          // const data = {
          //   token: '234435'
          // }

          commit('SET_TOKEN', data.token)
          storage.set('token', data.token)

          const roles = Array.isArray(data.menuWebList) ? data.menuWebList : []
          commit('SET_ROLES', roles)
          storage.set('roles', roles)

          commit('SET_USERINFO', data)
          // setCookie('user_info', data)
          localStorage.setItem('user_info', JSON.stringify(data))
        }

        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject(new Error('Verification failed, please Login again.'))
        }

        const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject(new Error('getInfo: roles must be a non-null array!'))
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  Logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_USERINFO', {})

      store.commit('SET_REQ', false)

      storage.remove('token')
      storage.remove('roles')
      localStorage.removeItem('user_info')

      resolve()
    })
  }
}

export default {
  state,
  mutations,
  actions
}
